#include "signinwidget.h"
#include "ui_signinwidget.h"

#include <QIcon>
#include <QRegExpValidator> // 正则表达式
#include <QSettings>
#include <QMessageBox>

#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QByteArray>
#include <QtNetwork/QNetworkReply>

#include "signupwidget.h"

SignInWidget::SignInWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SignInWidget)
{
    ui->setupUi(this);

    // 一些窗口风格
    this->setWindowTitle("登录");
    this->setWindowIcon(QIcon(":/img/res/icon.png"));
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint);

    // 用户名只能为数字或字母
    ui->lineEdit_username->setValidator(new QRegExpValidator(QRegExp("[a-zA-Z0-9]+$")));

    // 回车换行或登录
    connect(ui->lineEdit_username, &QLineEdit::returnPressed, [=]() {
        ui->lineEdit_password->setFocus();}
    );
    connect(ui->lineEdit_password, SIGNAL(returnPressed()), this, SLOT(on_pushButton_signIn_clicked()));

    // 读取记住的账号
    QSettings setting("./config.ini", QSettings::IniFormat);
    QString username = setting.value("username").toString();
    ui->lineEdit_username->setText(username);

    // 读取记住的密码
    bool rememberPassword = setting.value("rememberPassword").toBool();
    if (rememberPassword) {
        QString password = setting.value("password").toString();
        ui->checkBox_remember->setChecked(true);
        ui->lineEdit_password->setText(password);

        // 如果勾选记住密码，则再次打开软件时焦点设为密码框，否则是用户名框
        ui->lineEdit_password->setFocus();
    } else {
        ui->lineEdit_username->setFocus();
    }
}

SignInWidget::~SignInWidget()
{
    // 记住账号
    QSettings setting("./config.ini", QSettings::IniFormat);
    setting.setValue("username", ui->lineEdit_username->text());
    // 记住密码
    if (ui->checkBox_remember->isChecked()) {
        setting.setValue("password", ui->lineEdit_password->text());

        setting.setValue("rememberPassword", true);
    } else {
        setting.setValue("rememberPassword", false);
    }
    setting.sync();

    delete ui;
}

void SignInWidget::on_pushButton_signIn_clicked()
{
    QString username = ui->lineEdit_username->text();
    QString password = ui->lineEdit_password->text();

    if(username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, tr("警告"), tr("用户名或密码不能为空"), QMessageBox::Ok);
        return;
    }

    // http://localhost:8081/user/signin?username=123&password123
    m_request.setUrl(QUrl(m_signInUrl + "?username=" + username + "&" + "password=" + password));
    m_manager.get(m_request);
    connect(&m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(slot_finishRequest(QNetworkReply *)));

//    if(username == "admin" && password == "123456") {
//        this->close();
//        emit mainShow();
//    } else {
//        QMessageBox::warning(this, tr("登录失败"), tr("用户名或密码错误"), QMessageBox::Ok);
//        ui->lineEditPassword->clear();
//        ui->lineEditUsername->setFocus();
//    }
}

void SignInWidget::slot_finishRequest(QNetworkReply *reply) {
    if (reply->error()) {
        qDebug() << "Error!";
        QMessageBox::warning(this, tr("登录失败"), tr("请检查网络连接"), QMessageBox::Ok);
    } else {
        // 解析reply中携带的Json
        QByteArray byteArray = reply->readAll();
        QJsonParseError jsonParseError;
        QJsonDocument parseDocument = QJsonDocument::fromJson(byteArray, &jsonParseError);
        if (jsonParseError.error == QJsonParseError::NoError) {
            if (parseDocument.isObject()) {
                QJsonObject resultJsonObject = parseDocument.object();
                if (resultJsonObject.contains("success")) {
                    bool isSuccess = resultJsonObject.value("success").toBool();
                    if (isSuccess) {
                        this->close();
                        // 将登录后返回的结果传送给主窗口
                        resultJsonObject.insert("username", ui->lineEdit_username->text());
                        emit signal_signInSuccess(resultJsonObject);
                    } else {
                        QMessageBox::critical(this, "登录失败", resultJsonObject.value("message").toString(), QMessageBox::Ok);
                        ui->lineEdit_password->clear();
                        ui->lineEdit_username->setFocus();
                    }
                }
            }
        }
    }

    reply->deleteLater();
}

void SignInWidget::on_pushButton_signUp_clicked()
{
    SignUpWidget *signUpWidget = new SignUpWidget;
    signUpWidget->show();
}

